<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\ActivaCode;
use App\Models\ActivateList;
use Illuminate\Support\Facades\Auth;

class ActivaCodeController extends Controller
{
    // 生成随机激活码
    public function create(Request $request) {
        if ($request->one_time) {
            // 随机5位数
            $randstr = str_pad(random_int(1, 99999), 5, 0, STR_PAD_LEFT);
        } else {
            // 随机3位数
            $randstr = str_pad(random_int(1, 999), 3, 0, STR_PAD_LEFT);
        }
        // $randstr = $this->randstr();

        $ActivaCode = ActivaCode::where('code', $randstr )->first();
        if ($ActivaCode) {
            $this->create();
        }
        ActivaCode::create([
            'code' => $randstr,
            'name' => $request->name,
            'desc' => $request->desc,
            'one_time' => $request->one_time ? '1' : NULL
        ]);
        return $this->message('创建成功！');
    }

    public function randstr() {
        //字符组合
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $len = strlen($str)-1;
        $randstr = '';
        for ($i=0; $i< 6; $i++) {
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }
    
    // 校验激活码
    public function check(Request $request) {
        $userAuth = Auth::guard('api')->user();
        $user = User::find($userAuth->user_id);

        // if ($request->code == 'QHCJY99' || $request->code == '808') {
        //     $user->is_activated = 1;
        //     $user->save();
        //     return $this->message('激活成功！');
        // }

        $ActivaCode = ActivaCode::where(['code' => $request->code])->first();
        if (!$ActivaCode) {
            return $this->failed('无效的激活码！', 200);
        }
        if ($ActivaCode->one_time == '2') {
            return $this->failed('激活码已被使用！', 200);
        }

        $isActivete = ActivateList::where('user_id', $userAuth->user_id)->first();
        if ($isActivete) {
            return $this->failed('用户已激活，无需重复激活！', 200);
        }
        ActivateList::create([
            'code' => $request->code,
            'user_id' => $userAuth->user_id
        ]);
        if ($ActivaCode->one_time == '1') {
            $ActivaCode->one_time = '2';
            $ActivaCode->save();
        }

        $user->is_activated = 1;
        $user->save();
        return $this->message('激活成功！');
    }

    // 未激活的列表
    public function list(Request $request) {
        $codeList = ActivaCode::orderBy('created_at', 'desc')->paginate(10);
        return $this->success($codeList);
    }
}
